import 'dart:async';
import 'dart:io';
import 'dart:convert';
import 'dart:ui';


import 'package:flutter/material.dart';
import 'package:wis_flutter/index.dart';
import 'package:path/path.dart';
import 'package:file_picker/file_picker.dart';

// import 'package:flutter/widgets.dart';


// 文件 上传
class UploadFilePage extends StatefulWidget {

    final dynamic controller;      // 表单名称
    final String label;           // lable
    final bool validator;         // 校验
    final bool noAsync; // 同步

    final String validatorText;   // 校验提示
    final bool readOnly;          // 只读
    final dynamic onChanged;    // 值改变
    final dynamic onUpload;    //  上传 单个

    
    final dynamic onDeleteChildren;    // children 图片回调
    final dynamic onDelete;    // 删除 图片回调

    
    final List children;   // 自定义图片
    final double maxLimit; // 数量限制


    UploadFilePage({
        Key key,
        this.controller,
        this.label,
        this.validator=false,
        this.noAsync = false,  
        this.validatorText="必填",
        this.readOnly=false,   
        this.onChanged,
        this.onUpload,
        this.onDeleteChildren,
        this.onDelete,
        this.children,
        this.maxLimit=0

        
    }) : super(key: key);  

    @override
    _UploadFilePageState createState() => new _UploadFilePageState();
}

class _UploadFilePageState extends State<UploadFilePage> {

    List<File> _fileList=[];     // 文件 box
    List _fileNameList=[];       // 文件名 box


    // 初始化
    void initState() {
      super.initState();      

      this._setForm();  // 设置表单
    }

    @override
    void dispose() {
      super.dispose();
    }

    // 保存时间
    void _saveFunc(){

      // 回调
      if( widget.onChanged!=null ){
        widget.onChanged(_fileList); 
      } 

      this._setForm();  // 设置表单
    }

    // 设置表单
    void _setForm(){
      var len=(_fileList.length)+ ( (widget.children!=null)?widget.children.length:0);
      widget.controller.text= len>0?jsonEncode(len):'';
    }

    // 删除
    void _deleteFunc(j){

      List<File> _newList=[];

      for (var i = 0; i < _fileList.length; i++) {
        if( i!=j ){
          _newList.add(_fileList[i]);
        }
      }
      
      setState(() {
        _fileList=_newList;
      });      
      
      this._saveFunc(); // 保存
    }
 

    // 文件 选择
    Future _getFileFrom(context) async {

      List<File> files = await FilePicker.getMultiFile();

      // 未选择
      if( files==null ) return;


      // 限制 数量
      if( widget.maxLimit>0 ){
        if( ( ( (widget.children!=null)?widget.children.length:0)+files.length+_fileList.length ) > widget.maxLimit ) {
          WisMessageGlobal.warning(
            context:context,
            title:"已达上限！",   
            content: '最多上传文件数量为【${widget.maxLimit.floor().toString()}】'
          );
          return;
        }
      }

      // 文件名 
      List names = files.map((e){
        return basename(e.path);
      }).toList(); 


      // 单个 上传 回调
      if( widget.onUpload!=null ){
        widget.onUpload(files); 
      } 

      // 异步
      if( widget.onUpload == false ){
        _fileList.addAll(files);
        _fileNameList.addAll(names);

        setState(() {
          
        });

        this._saveFunc(); // 保存
      }
    }



    // 遍历 自定义 文件 
    Widget _bodyInit(context) {

        if( widget.children==null ){
          return Container(
            child: null
          );
        }


        
        List<Widget> _list = [];

        // Widget content; 
        for (var i = 0; i < widget.children.length; i++) {

          _list.add(
            Padding(
              padding: EdgeInsets.fromLTRB(6,6,6,6),
              child: Container(
                child: Stack(
                  children: <Widget>[
                    Container(
                      // color: Colors.red,
                      height: 36,
                      child: Row(
                      children: <Widget>[
                        Expanded(
                          flex: 8,
                          child: Container(
                            padding: EdgeInsets.fromLTRB(0,6,0,6),
                            // color: Colors.red,
                            child: Text(
                              widget.children[i]["fileName"].toString(),
                              overflow: TextOverflow.ellipsis,
                            ),
                          )
                        ),
                        Expanded(
                          flex: 1,
                          child: widget.children[i]["onDownload"]!=null ?Container(
                            margin: EdgeInsets.fromLTRB(0,0,0,10),
                            width: 22,
                            height: 22,
                            child: IconButton(
                              icon: Icon(Icons.file_download ),
                              onPressed: (){
                                if( widget.children[i]["onDownload"]!=null ){
                                  widget.children[i]["onDownload"](widget.children[i]);
                                }
                              },
                              tooltip: '下载',
                              color: Colors.blue,
                            )                            
                          ):Text(''),
                        ),                        
                        Expanded(
                          flex: 1,
                          child: !widget.readOnly ? Container(
                            // padding: EdgeInsets.fromLTRB(0,0,0,16),
                            margin: EdgeInsets.fromLTRB(0,0,0,16),
                            // margin: EdgeInsets.fromLTRB(6,24,0,0),
                            width: 22,
                            height: 22,
                            child: IconButton(
                              icon: Icon(Icons.close),
                              onPressed: (){
                                if( widget.onDeleteChildren!=null ){
                                  widget.onDeleteChildren(widget.children[i]);
                                }
                              },
                              tooltip: '删除',
                              color: Colors.redAccent,
                            )                           
                          ):Text(""),
                        )
                      ],
                    ),
                    )


                  ],
                ),
              )
            ),
          );
        }


        return Wrap(
          children:_list.toList()
        );
    }


    // 遍历 上传文件
    Widget _bodyUploading(context) {

        List<Widget> _list = [];

        // Widget content; 
          for (var i = 0; i < _fileList.length; i++) {

          _list.add(
            Padding(
              padding: EdgeInsets.fromLTRB(6,6,6,6),
              child: Container(
                child: Stack(
                  children: <Widget>[
                    Container(
                      // color: Colors.red,
                      height: 30,
                      child: Row(
                      children: <Widget>[
                        Expanded(
                          flex: 8,
                          child: Text(
                            _fileNameList[i].toString(),
                            overflow: TextOverflow.ellipsis,
                          )
                        ),
                        Expanded(
                          flex: 2,
                          child: Container(
                            // margin: EdgeInsets.fromLTRB(6,24,0,0),
                            width: 22,
                            height: 22,
                            child: IconButton(
                              icon: Icon(Icons.close),
                              onPressed: (){
                                if( widget.onDelete!=null ){
                                  widget.onDelete(_fileList[i]);
                                }                                
                                this._deleteFunc(i);
                              },
                              tooltip: '删除',
                              color: Colors.redAccent,
                            )                                                                                                 
                          ),
                        )
                      ],
                    ),
                    )





                  ],
                ),
              )
            ),
          );
        }


        return Wrap(
          children:_list.toList()
        );
    }


    @override
    Widget build(BuildContext context) {
        return Padding(
          padding: EdgeInsets.fromLTRB(16,32,16,16),
          child:  Container(
            // color: Colors.white,
            child: Stack(
                children: <Widget>[

                  Container(
                    child: !widget.readOnly ? Container(
                      margin: EdgeInsets.fromLTRB(0,38,0,0),
                      child: Row(
                        children: <Widget>[
                          Container(
                            margin: EdgeInsets.fromLTRB(8,0,0,0),
                            child: Ink(
                              decoration: const ShapeDecoration(
                                color: Colors.lightBlue,
                                shape: CircleBorder(),
                              ),
                              child: IconButton(
                                onPressed: (){
                                  this._getFileFrom(context);
                                },
                                tooltip: '添加',
                                icon: Icon(Icons.add),
                                color: Colors.white,
                              )
                            ),
                          ),
                        ],
                      )
                    ):
                    Text("")
                  ),

                  Container(
                    // padding: EdgeInsets.fromLTRB(0,0,0,16),
                    child: Row(
                      children: <Widget>[

                        Text(
                          widget.validator?'*':'',
                          textAlign: TextAlign.left,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              fontSize: 14,
                              color: Colors.red
                          )
                        ),  

                        Text(
                          widget.label.toString(),
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              fontSize: 14,
                              color: const Color.fromRGBO(81,90,110,1)
                          ),
                        )
                      ],
                    ),
                  ),

                  Container(
                    // margin: EdgeInsets.fromLTRB(0,30,0,0),
                    margin: !widget.readOnly ? EdgeInsets.fromLTRB(0,92,0,0) : EdgeInsets.fromLTRB(0,38,0,0),

                    // color: Colors.red,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[

                        this._bodyInit(context),       // 自定义图片
                        this._bodyUploading(context),  // 上传

                        
                        Container(
                          margin: EdgeInsets.fromLTRB(0,50,0,0),
                          // color: Colors.red,
                          child: !widget.readOnly ? Stack(
                            children: <Widget>[

                              Container(
                                margin: EdgeInsets.fromLTRB(0,0,0,0),
                                child: Row(
                                  children: <Widget>[
                                    Expanded(
                                      child: TextFormField(
                                        controller: widget.controller,                            
                                        autofocus: false,
                                        readOnly: true,
                                        style: TextStyle(
                                          color: Colors.transparent,
                                        ),
                                        decoration: InputDecoration(
                                            // labelText: widget.label,
                                            labelStyle: TextStyle( 
                                                fontSize: 14.0, 
                                                color: Color.fromARGB(255, 93, 93, 93)
                                            ),
                                            enabledBorder: UnderlineInputBorder(
                                              borderSide: BorderSide(width:0.5,color: Colors.grey[500]),
                                            ),
                                            focusedBorder: UnderlineInputBorder(
                                              borderSide: BorderSide(width:0.5,color: Colors.blue),
                                            ),
                                            errorBorder: UnderlineInputBorder(
                                              borderSide: BorderSide(width:0.5,color: Colors.red),
                                            ),                                    
                                        ),
                                        validator: widget.validator ? (value) {
                                          if (value.isEmpty) {
                                            return widget.validatorText;
                                          }
                                          return null;
                                        }:null,
                                      )
                                    )
                                  ],
                                ),
                              )
                            ],
                          ):null,
                        ),


                      ],
                    ),
                  ),

                ]
            )   
          )  
        );
    }  
}


